﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DeployGames.TweenEngine
{
    public abstract class Pool<T>
    {
        private List<T> objects;
        private Callback<T> callback;

        protected abstract T create();

        public Pool(int initCapacity, Callback<T> callback)
        {
            this.objects = new List<T>(initCapacity);
            this.callback = callback;
        }

        public T get()
        {
            T obj = default(T);
            if (objects.Count == 0)
            {
                obj = create();
            }
            else
            {
                obj = objects[objects.Count - 1];
                objects.RemoveAt(objects.Count - 1);
            }
            if (callback != null) callback.onUnPool(obj);
            return obj;
        }

        public void free(T obj)
        {
            if (!objects.Contains(obj))
            {
                if (callback != null) callback.onPool(obj);
                objects.Add(obj);
            }
        }

        public void clear()
        {
            objects.Clear();
        }

        public int size()
        {
            return objects.Count;
        }

        public void ensureCapacity(int minCapacity)
        {
            objects.Capacity = minCapacity;
        }
    }
}
